<template>
  <div class="customer-table-box">
    <PlainCreateBtn v-if="isEdit" :class="{'mobile-contact-btn': showMobilePage}" class="add-btn" @click="addContact">添加客户联系人</PlainCreateBtn>
    <dynamicEditTable
      v-loading="loading"
      v-if="flag"
      ref="dynamicContactTable"
      v-model="contactData"
      :list-data="contactData"
      :list-data-count="contactDataCount"
      :list-setting="contactSetting"
      :is-edit="isEdit"
      :show-serial="false"
      :show-add-btn="false"
      :show-copy-btn="false"
      :can-empty="true"
      :has-border="false"
      :row-del-auth="true"
      :row-del-auth-str="delAuthStr"
      :del-tip-str="'请确定是否删除该联系人'"
      :open-page="isEdit"
      visible-change-data
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @delRowData="delContact"
      @scrollSelectChange="scrollSelectChange"
      @handleCheckSecretVal="handleCheckSecretVal"
    />
    <!-- :append-to-body="false" -->
  </div>
</template>

<script>
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import { contactSetting } from '../data';
import { arrRepeat } from '@/utils/tools';
import { mapState } from 'vuex';

export default {
  name: 'ContactTable',
  components: {
    dynamicEditTable
  },
  model: {
    prop: 'contactData',
    event: 'changeValue'
  },
  props: {
    contactData: {
      type: Array,
      default() {
        return [];
      }
    },
    contactDataCount: {
      type: Number,
      default: 0
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    loading: {
      type: Boolean,
      default: false
    },
    deptTreeList: {
      type: Array,
      default() {
        return [];
      }
    },
    delAuthStr: {
      type: String,
      default: 'crm:customer:deleteContact'
    },
    orderPrivateId: {
      type: Number,
      default: 0
    },
    isPageEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      contactSetting,
      flag: true
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  watch: {
    deptTreeList(newVal) {
      if (newVal) {
        this.flag = false;
        this.$nextTick(() => {
          this.flag = true;
        });
        for (let i = 0; i < this.contactSetting.length; i++) {
          if (this.contactSetting[i].keyword === 'coDepartment') {
            this.contactSetting[i].options = this.deptTreeList;
            break;
          }
        }
        return this.contactSetting;
      }
    }
  },
  mounted() {
    if (!this.isPageEdit && this.contactData.length === 0) {
      this.addContact();
    }
  },
  methods: {
    arrRepeat,
    validate() {
      return this.$refs.dynamicContactTable.validate();
    },
    addContact() {
      const curContact = {
        contactPerson: '',
        tel: '',
        creator: '--',
        createTime: '--',
        department: '--',
        isAdd: true,
        status: 1,
        orderPrivateId: this.orderPrivateId + 1
      };
      this.$emit('orderPrivateIdChange', this.orderPrivateId + 1);
      this.contactData.unshift(curContact);
    },
    setFirstSelectTag() {
      this.$nextTick(() => {
        this.$refs['dynamicContactTable'].firstInitPanel = true;
      });
    },
    handleSizeChange(val) {
      this.$emit('handleSizeChange', val);
    },
    handleCurrentChange(val) {
      this.$emit('handleCurrentChange', val);
    },
    delContact(val) {
      this.$emit('delContact', val);
    },
    handleCheckSecretVal(rowData) {
      this.$emit('handleCheckSecretVal', rowData);
    },
    // 协作人变更增加默认名称
    scrollSelectChange(key, data, rowIndex) {
      const index = this.contactData.findIndex(el => el.orderPrivateId === data.orderPrivateId);
      delete data.orderPrivateId;
      if (index !== -1) {
        this.$set(this.contactData[index], 'associateList', [...data]);
      }
      // 选择协作人自动填充人员的子部门为协作部门
      if (data && data.length) {
        // 拼接用户的子级部门，还要去重
        let temp = [];
        data.forEach(item => {
          temp = temp.concat(item.currentDepartment);
        });
        const res = this.arrRepeat(temp);
        const resId = res.map(item => {
          return item.id;
        });
        this.$set(this.contactData[rowIndex], 'coDepartment', resId);
        const resName = res.map(item => {
          return item.name;
        }).join();
        this.$set(this.contactData[rowIndex], 'coDepartmentName', resName);
      } else {
        this.$set(this.contactData[rowIndex], 'coDepartment', []);
        this.$set(this.contactData[rowIndex], 'coDepartmentName', '');
      }
    }
  }
};
</script>
<style lang="scss" scoped>
  .mobile-contact-btn {
    border-radius: 4px !important;
  }
</style>
